package cn.gl.org.service.impl;

import cn.gl.basic.service.impl.BaseServiceImpl;
import cn.gl.basic.util.PageList;
import cn.gl.org.domain.Department;
import cn.gl.org.mapper.DepartmentMapper;
import cn.gl.org.query.DepartmentQuery;
import cn.gl.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import java.util.Map;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public List<Department> deptTree() {
        //查询出所有数据
        List<Department> departments = departmentMapper.laodAll();
        //创建个map对象  k为id  value为department
        Map<Long, Department> map = new HashMap<>();
        //循环遍历把查出的所有department对象装入map
        for (Department department : departments){
            //put是map中奖数据保存到map中的方法
            map.put(department.getId(), department);
        }
        List<Department> deptTree = new ArrayList<>();
        //遍历所有的部门
        for (Department department : departments) {
            if(department.getParent_id() == null){//顶级部门
                //添加到部门树
                deptTree.add(department);
            }else{//有父级部门
                Long parent_id = department.getParent_id();//父部门id
                //获取父部门对象
                Department parentDepartment = map.get(parent_id);
                if(parentDepartment != null){
                    //将自己状态父部门的children集合中
                    parentDepartment.getChildren().add(department);
                }
            }
        }

        return deptTree;
    }

}
